<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<th:block th:include="include :: header('识别列表')" />
	<style>
		/* 自定义模态框的样式 *//* 调整模态框的对话框样式 */
		#imageModal .modal-dialog {
			position: fixed;
			z-index: 1050;
			left: 0;
			top: 0;
			width: 90%; /* 调整宽度 */
			height: 90%; /* 调整高度 */
			background-color: rgba(0, 0, 0, 0.4);
			display: flex;
			justify-content: center;
			align-items: center;
			overflow: auto;
			padding: 0; /* 去除内边距 */
		}

		/* 添加CSS样式，使文件名居中 */
		.image-container {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			margin: 10px;
		}

		.image-name {
			text-align: center;   /* 确保文本居中 */
			margin-top: 10px;      /* 图片和名称之间的间距 */
			font-size: 20px;       /* 调整字体大小，可根据需要修改 */
		}


		/* 调整模态框内容区域 */
		#imageModal .modal-content {
			max-width: 100%;
			max-height: 100%;
			overflow: auto;
			background-color: #fff;
			padding: 20px;
			border-radius: 8px;
			position: relative;
		}

		/* 图片样式 */
		#imageContainer img {
			max-width: 100%;
			max-height: 80vh; /* 设定最大高度 */
			height: auto;
			display: block;
			margin: 0 auto; /* 居中图片 */
		}
		.progress {
			margin-top: 18px;
		}
		/*按钮下间距*/
		.button-spacing {
			margin-bottom: 5px; /* 根据需要调整 */
		}
	</style>
</head>
<body class="gray-bg">
     <div class="container-div">
		<div class="row">
			<div class="col-sm-12 search-collapse">
				<form id="formId">
					<div class="select-list">
						<ul>
							<li>
								所选识别任务的名称：<input type="text" name="trainMissionName"/>
							</li>
							<li>
								所识别数据集名称：<input type="text" name="datasetName"/>
							</li>

							<li>
								识别状态：<input type="text" name="status"/>
							</li>

<!--							<li>-->
<!--								开始识别时间：<input type="text" name="beginTime"/>-->
<!--							</li>-->

<!--							<li>-->
<!--								结束识别时间：<input type="text" name="endTime"/>-->
<!--							</li>-->

							<li>
								<a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i class="fa fa-search"></i>&nbsp;搜索</a>
								<a class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()"><i class="fa fa-refresh"></i>&nbsp;重置</a>
							</li>
						</ul>
					</div>
				</form>
			</div>
			
	        <div class="btn-group-sm" id="toolbar" role="group">
				<a class="btn btn-success" onclick="$.operate.add()" shiro:hasPermission="deep_learning:predict:add">
					<i class="fa fa-plus"></i> 添加
				</a>
			</div>
			<div class="col-sm-12 select-table table-striped">
				<table id="bootstrap-table" class="table table-bordered" data-mobile-responsive="true"></table>
			</div>
		</div>
	</div>
	 <!-- 图片模态框 -->
	 <div class="modal fade" id="imageModal" tabindex="-1" role="dialog" aria-labelledby="imageModalLabel" aria-hidden="true">
		 <div class="modal-dialog modal-lg" role="document">
			 <div class="modal-content">
				 <div class="modal-header">
					 <h5 class="modal-title" id="imageModalLabel" style="font-size: 18px;">图片预览</h5>
					 <button type="button" class="close" data-dismiss="modal" aria-label="Close">
						 <span aria-hidden="true">&times;</span>
					 </button>
				 </div>
				 <div class="modal-body">
					 <div id="imageContainer" class="files-container"></div>
					 <nav aria-label="Page navigation">
						 <ul class="pagination" id="pagination">
							 <!-- 分页按钮将在这里动态插入 -->
						 </ul>
					 </nav>
				 </div>
			 </div>
		 </div>
	 </div>


	 <div th:include="include :: footer"></div>
    <script th:inline="javascript">
        var editFlag = [[${@permission.hasPermi('deep_learning:predict:edit')}]];
        var removeFlag = [[${@permission.hasPermi('deep_learning:predict:remove')}]];
        var prefix = ctx + "deep_learning/predict";
		var currentUserId = null;
		$.ajax({
			url: '/deep_learning/app01Dataset/currentUser', // 此地址返回当前用户的 userId
			method: 'GET',
			success: function (response) {
				console.log("response.userId", response.userId)
				currentUserId = response.userId;
			},
			error: function (xhr, status, error) {
				console.error('请求当前用户信息失败:', error);
			}
		}).then(function () {
			if (currentUserId !=1){
				var options = {
					url: prefix + "/list",
					createUrl: prefix + "/add",
					updateUrl: prefix + "/edit/{id}",
					removeUrl: prefix + "/remove",
					exportUrl: prefix + "/export",
					modalName: "识别任务",
					showExport: true,
					sidePagination: 'client', // 前端分页
					columns: [
						{
							field : 'id',
							title : 'id',
							visible: false
						},
						{
							field : 'predictName',
							title : '识别任务名称',
							align: 'center',
							sortable: true
						},
						{
							field: 'userName',
							title: '归属用户',
							align: 'center',
							sortable: true
						},
						{
							field : 'trainMissionName',
							title : '所选任务的名称',
							align: 'center',
							sortable: true
						},
						{
							field : 'datasetName',
							title : '识别数据集名称',
							align: 'center',
							sortable: true
						},
						{
							field : 'status',
							title : '识别状态',
							align: 'center',
							formatter: function (value, row, index) {
								var statusText = '';
								var color = '';
								switch (value) {
									case '未识别':
										statusText = '未识别';
										color = 'gray';
										break;
									case '待识别':
										statusText = '待识别';
										color = 'orange';
										break;
									case '识别中':
										statusText = '识别中';
										color = 'blue';
										break;
									case '已完成':
										statusText = '已完成';
										color = 'green';
										break;
									case '转化格式':
										statusText= '转化格式';
										color='purple';
										break;
									default:
										statusText = '识别异常';
										color = 'black';
								}
								return '<span style="color: ' + color + ';">' + statusText + '</span>';
							},
							sortable: true
						},
						{
							field : 'beginTime',
							title : '开始识别时间',
							align: 'center',
							sortable: true
						},
						{
							field : 'endTime',
							title : '结束识别时间',
							align: 'center',
							sortable: true
						},
						{
							//     进度条
							field: 'progress',
							title: '进度',
							align: 'center',
							formatter: function (value, row, index) {
								if (value === null) {
									return '';
								}

								// 创建一个容器，用于显示进度条
								var progressBarContainer = '<div id="progress-bar-' + row.id + '" class="progress progress-striped active">' +
										'<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">' +
										'0%' +
										'</div>' +
										'</div>';
								// 定义一个函数来更新进度条
								function updateProgressBar() {
									$.ajax({
										url: '/deep_learning/predict/getProgress/' + row.id, // 根据行ID获取进度数据的API地址
										method: 'GET',
										success: function (progressData) {
											if (progressData.status === "success") {
												var progressValue = progressData.data;
												$('#progress-bar-' + row.id + ' .progress-bar').css('width', progressValue + '%').css('color', 'black').attr('aria-valuenow', progressValue).text(progressValue + '%');
												// 如果进度未达到 100%，继续定期轮询
												if (progressValue < 100) {
													setTimeout(updateProgressBar, 500); // 每5秒轮询一次
												}else {
													// if(row.status === "识别中"){
													// 	let refreshButton = $("button[name='refresh']");
													// 	setTimeout(refreshButton.click(), 1000);
													// }
												}
												row.progress=progressValue;
											} else {
												console.error('Failed to fetch progress data:', progressData.message);
											}
										},
										error: function (xhr, status, error) {
											console.error('Failed to fetch progress data:', error);
										}
									});
								}

								// 初次调用更新进度条
								updateProgressBar();
								return progressBarContainer;
							},
							sortable: true
						},
						{
							field: 'queuePosition',
							title: '队列位次',
							align: 'center',
							sortable: true,
							sorter: function (a, b) {
								var aValue = a === null ? Infinity : a; // 将空值视为-1
								var bValue = b === null ? Infinity : b;
								return aValue - bValue;
							},
							formatter: function (value, row, index) {
								// 定义一个容器，用于显示队列位次
								var queuePositionContainer = '<div id="queue-position-' + row.id + '">加载中...</div>';

								// 定义一个函数来更新队列位次
								function updateQueuePosition() {
									$.ajax({
										url: '/deep_learning/predict/getQueuePosition/' + row.id,  // 使用GET请求并将row.id作为路径参数传递
										method: 'GET',
										success: function (response) {
											if (response.queuePosition !== null) {
												// 如果返回了有效的队列位次，则更新显示
												$('#queue-position-' + row.id).text(response.queuePosition);
											} else {
												// 如果返回的是null，则显示空值
												// $('#queue-position-' + row.id).text('N/A');
												$('#queue-position-' + row.id).text('');
											}
											row.queuePosition=response.queuePosition
										},
										error: function (xhr, status, error) {
											console.error('Failed to fetch queue position:', error);
											$('#queue-position-' + row.id).text('错误');
										}
									});
								}

								// 初次调用更新队列位次
								updateQueuePosition();

								return queuePositionContainer;
							}
						},
						{
							title: '操作',
							align: 'center',
							formatter: function(value, row, index) {
								var actions = [];
								var startButton = '<a class="btn btn-success btn-xs button-spacing" href="javascript:void(0)" data-id="' + row.id + '" onclick="$.operate.startSingleInference(\'' + row.id + '\')" style="background-color: gray; border-color: gray;"><i class="fa fa-play" style="color: green;"></i> 启动</a>';
								var stopButton = '<a class="btn btn-danger btn-xs button-spacing" href="javascript:void(0)" data-id="' + row.id + '" onclick="$.operate.stopSingleInference(\'' + row.id + '\')" style="background-color: white; border-color: red; color: red;"><i class="fa fa-stop" style="color: red;"></i> 终止</a>';
								var addButton = '<a class="btn btn-primary btn-xs add-task button-spacing" href="javascript:void(0)"  onclick="$.operate.addToPredictList(this, \'' + row.id + '\')"><i class="fa fa-plus"></i> 添加识别队列</a>';
								var removePredictButton = '<a class="btn btn-danger btn-xs remove-task button-spacing" href="javascript:void(0)" data-id="' + row.id + '" onclick="$.operate.removeFromPredictList(this, \'' + row.id + '\')"><i class="fa fa-minus"></i> 移除识别队列</a>';
								var removeButton = '<a class="btn btn-danger btn-xs button-spacing ' + removeFlag + '" href="javascript:void(0)" onclick="$.operate.removeInferenceResult(\'' + row.id + '\')"><i class="fa fa-remove"></i>删除</a>';
								if (row.status === "未识别") {
									actions.push(addButton)
									actions.push(startButton);
								}else if(row.status === "待识别"){
									actions.push(removePredictButton)
								}
								if (row.status === "识别中") {
									// 如果任务正在运行，显示终止按钮
									actions.push(stopButton);

								} else {
									actions.push('<a class="btn btn-success btn-xs button-spacing ' + editFlag + '" href="javascript:void(0)" onclick="$.operate.edit(\'' + row.id + '\')"><i class="fa fa-edit"></i>编辑</a> ');
									actions.push(removeButton)

								}

								if (row.status === "已完成") {
									actions.push('<a class="btn btn-info btn-xs button-spacing" href="javascript:void(0)" onclick="$.operate.viewInferenceResult(\'' + row.id + '\')"><i class="fa fa-eye"></i>查看</a>'); // 新增的“查看”按钮
									// 	添加一个下载按钮, 下载识别结果,颜色为灰色
									actions.push('<a class="btn btn-info btn-xs button-spacing" href="javascript:void(0)" onclick="$.operate.downloadInferenceResultZip(\'' + row.id + '\')" style="background-color: gray; border-color: gray;"><i class="fa fa-download"></i>下载</a>');
								}
								return actions.join(' ');
							}
						}]
				};
				$.table.init(options);
			}
			else {
				var options = {
					url: prefix + "/listAdmin",
					createUrl: prefix + "/add",
					updateUrl: prefix + "/edit/{id}",
					removeUrl: prefix + "/remove",
					exportUrl: prefix + "/export",
					modalName: "识别任务",
					showExport: true,
					sidePagination: 'client', // 前端分页
					columns: [
						{
							field : 'id',
							title : 'id',
							visible: false
						},
						{
							field : 'predictName',
							title : '识别任务名称',
							align: 'center',
							sortable: true
						},
						{
							field: 'userName',
							title: '归属用户',
							align: 'center',
							sortable: true
						},
						{
							field : 'trainMissionName',
							title : '所选任务的名称',
							align: 'center',
							sortable: true
						},
						{
							field : 'datasetName',
							title : '识别数据集名称',
							align: 'center',
							sortable: true
						},
						{
							field : 'status',
							title : '识别状态',
							align: 'center',
							formatter: function (value, row, index) {
								var statusText = '';
								var color = '';
								switch (value) {
									case '未识别':
										statusText = '未识别';
										color = 'gray';
										break;
									case '待识别':
										statusText = '待识别';
										color = 'orange';
										break;
									case '识别中':
										statusText = '识别中';
										color = 'blue';
										break;
									case '已完成':
										statusText = '已完成';
										color = 'green';
										break;
									case '转化格式':
										statusText= '转化格式';
										color='purple';
										break;
									default:
										statusText = '识别异常';
										color = 'black';
								}
								return '<span style="color: ' + color + ';">' + statusText + '</span>';
							},
							sortable: true
						},
						{
							field : 'beginTime',
							title : '开始识别时间',
							align: 'center',
							sortable: true
						},
						{
							field : 'endTime',
							title : '结束识别时间',
							align: 'center',
							sortable: true
						},

						{
							//     进度条
							field: 'progress',
							title: '进度',
							align: 'center',
							formatter: function (value, row, index) {
								if (value === null) {
									return '';
								}

								// 创建一个容器，用于显示进度条
								var progressBarContainer = '<div id="progress-bar-' + row.id + '" class="progress progress-striped active">' +
										'<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">' +
										'0%' +
										'</div>' +
										'</div>';
								// 定义一个函数来更新进度条
								function updateProgressBar() {
									$.ajax({
										url: '/deep_learning/predict/getProgress/' + row.id, // 根据行ID获取进度数据的API地址
										method: 'GET',
										success: function (progressData) {
											if (progressData.status === "success") {
												var progressValue = progressData.data;
												// var finished=progressData.finished;
												$('#progress-bar-' + row.id + ' .progress-bar').css('width', progressValue + '%').css('color', 'black').attr('aria-valuenow', progressValue).text(progressValue + '%');

												// 如果进度未达到 100%，继续定期轮询
												if (progressValue < 100) {
													setTimeout(updateProgressBar, 500);
														// 每0.5秒轮询一次
												}else {
													// if(row.status === "识别中"){
													// 	let refreshButton = $("button[name='refresh']");
													// 	refreshButton.click();
													// }
												}
												row.progress=progressValue;
											} else {
												console.error('Failed to fetch progress data:', progressData.message);
											}
										},
										error: function (xhr, status, error) {
											console.error('Failed to fetch progress data:', error);
										}
									});
								}

								// 初次调用更新进度条
								updateProgressBar();
								return progressBarContainer;
							},
							sortable: true
						},
						{
							field: 'queuePosition',
							title: '队列位次',
							align: 'center',
							sortable: true,
							sorter: function (a, b) {
								var aValue = a === null ? Infinity : a; // 将空值视为-1
								var bValue = b === null ? Infinity : b;
								return aValue - bValue;
							},
							formatter: function (value, row, index) {
								// 定义一个容器，用于显示队列位次
								var queuePositionContainer = '<div id="queue-position-' + row.id + '">加载中...</div>';

								// 定义一个函数来更新队列位次
								function updateQueuePosition() {
									$.ajax({
										url: '/deep_learning/predict/getQueuePosition/' + row.id,  // 使用GET请求并将row.id作为路径参数传递
										method: 'GET',
										success: function (response) {
											if (response.queuePosition !== null) {
												// 如果返回了有效的队列位次，则更新显示
												$('#queue-position-' + row.id).text(response.queuePosition);
											} else {
												// 如果返回的是null，则显示空值
												// $('#queue-position-' + row.id).text('N/A');
												$('#queue-position-' + row.id).text('');
											}
											row.queuePosition=response.queuePosition
										},
										error: function (xhr, status, error) {
											console.error('Failed to fetch queue position:', error);
											$('#queue-position-' + row.id).text('错误');
										}
									});
								}

								// 初次调用更新队列位次
								updateQueuePosition();

								return queuePositionContainer;
							}
						},
						{
							title: '操作',
							align: 'center',
							formatter: function(value, row, index) {
								var actions = [];
								var startButton = '<a class="btn btn-success btn-xs button-spacing" href="javascript:void(0)" data-id="' + row.id + '" onclick="$.operate.startSingleInference(\'' + row.id + '\')" style="background-color: gray; border-color: gray;"><i class="fa fa-play" style="color: green;"></i> 启动</a>';
								var stopButton = '<a class="btn btn-danger btn-xs button-spacing" href="javascript:void(0)" data-id="' + row.id + '" onclick="$.operate.stopSingleInference(\'' + row.id + '\')" style="background-color: white; border-color: red; color: red;"><i class="fa fa-stop" style="color: red;"></i> 终止</a>';
								var addButton = '<a class="btn btn-primary btn-xs add-task button-spacing" href="javascript:void(0)"  onclick="$.operate.addToPredictList(this, \'' + row.id + '\')"><i class="fa fa-plus"></i> 添加识别队列</a>';
								var removePredictButton = '<a class="btn btn-danger btn-xs remove-task button-spacing" href="javascript:void(0)" data-id="' + row.id + '" onclick="$.operate.removeFromPredictList(this, \'' + row.id + '\')"><i class="fa fa-minus"></i> 移除识别队列</a>';
								var removeButton = '<a class="btn btn-danger btn-xs button-spacing ' + removeFlag + '" href="javascript:void(0)" onclick="$.operate.removeInferenceResult(\'' + row.id + '\')"><i class="fa fa-remove"></i>删除</a>';
								if (row.status === "未识别") {
									actions.push(addButton)
									actions.push(startButton);
								}else if(row.status === "待识别"){
									actions.push(removePredictButton)
								}
								if (row.status === "识别中") {
									// 如果任务正在运行，显示终止按钮,编辑按钮，删除按钮
									actions.push(stopButton);
									// actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="$.operate.edit(\'' + row.id + '\')"><i class="fa fa-edit"></i>编辑</a> ');
									actions.push(removeButton)



								} else {
									actions.push('<a class="btn btn-success btn-xs  button-spacing' + editFlag + '" href="javascript:void(0)" onclick="$.operate.edit(\'' + row.id + '\')"><i class="fa fa-edit"></i>编辑</a> ');
									actions.push(removeButton)

								}
								if (row.status === "已完成") {
									actions.push('<a class="btn btn-info btn-xs button-spacing" href="javascript:void(0)" onclick="$.operate.viewInferenceResult(\'' + row.id + '\')"><i class="fa fa-eye"></i>查看</a>'); // 新增的“查看”按钮
									// 	添加一个下载按钮, 下载识别结果,颜色为灰色
									actions.push('<a class="btn btn-info btn-xs button-spacing" href="javascript:void(0)" onclick="$.operate.downloadInferenceResultZip(\'' + row.id + '\')" style="background-color: gray; border-color: gray;"><i class="fa fa-download"></i>下载</a>');
								}
								return actions.join(' ');
							}
						}]
				};
				$.table.init(options);
			}
		});
		window.addEventListener('message', function (event) {
			console.log("收到来自子窗口的消息：")
			setTimeout(function () {
				let refreshButton = $("button[name='refresh']");
				refreshButton.click();
				// $.table.refresh();
			}, 80)
		});
    </script>
</body>
</html>